import imaplib
import email
from email.header import Header, decode_header, make_header
from email.message import EmailMessage
from email.utils import parsedate
import re
import ipaddress
import os

#подключение к серверу
imap = imaplib.IMAP4_SSL('imap.yandex.ru')
imap.login('mail@yandex.ru', 'pass')

#выбор каталога
imap.select('access')

#просмотр непрочитанных (u-unread)
r, d = imap.search(None, '(UNSEEN)')
c = str(d)
carray = []
regex = r"\d{1,4}|10000$"
matches = re.finditer(regex, c, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
   carray.extend ("{match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
i = len(carray)
ii=0

def check_ip(ip):
    try:
        ipaddress.ip_address(ip)
    except ValueError:
        return 0
    else:
        return 1

while ii < i:
    result, data = imap.search(None, '(UNSEEN)')
    ids = data[0] # Получаем сроку номеров писем
    id_list = ids.split() # Разделяем ID писем
    latest_email_id = id_list[-1] # Берем последний ID
    result, data = imap.fetch(latest_email_id, "(RFC822)") # Получаем тело письма (RFC822) для данного ID
    raw_email = data[0][1] # Тело письма в необработанном виде
    email_message = email.message_from_bytes(raw_email)
    efrom = make_header(decode_header(email_message['From']))
    esubject = make_header(decode_header(email_message['Subject']))
    sesubject = str(esubject)
    edate = email_message['Date']
    ipv = check_ip(str(esubject))
    f = open('log.txt', 'a')
    f.write(edate)
    f.write('  ')
    f.write(str(efrom))
    f.write('  IP:')
    f.write(str(esubject))
    f.write('  ')
    f.close()
    print('Log1 updated')
    if ipv == 1:
          f = open('access.txt', 'a')
          f.write(sesubject)
          f.write(',')
          f.close()
          print('Access list updated')
    else:
          f = open('log.txt', 'a')
          f.write('WARNONG INVALID IP:')
          f.write(sesubject)
          f.close()
          print('Log2 updated')
    f = open('log.txt', 'a')
    f.write('\n')
    f.close()
    
    ii = ii+1
    if ii == i:
       break

f = open('access.txt', 'r')
ipslist = f.read().split(",")
f.close()
ips = (','.join(ipslist))
ips = str(ips)
os.system('netsh advfirewall firewall set rule name="Remote Desktop - User Mode (TCP-In)" new remoteip='+str(ips))


 


#netsh advfirewall firewall set rule name=test new remoteip=
#netsh advfirewall firewall set rule name="Дистанционное управление рабочим столом (TCP - входящий)" new remoteip=
